/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="gis-planchart" v-if="isPanelShow">
    <div class="route-header">
      <div class="title">
        <el-tooltip v-if="routeName && routeName > 15" placement="bottom-start" effect="dark">
          <div slot="content">{{routeName}}</div>
          <span class="devname">{{routeName && routeName.substr(0, 15) + '...'}}</span>
        </el-tooltip>
        <span v-else>{{routeName}}</span>
      </div>
      <div class="close" @click="onCloseClick"><i class="el-icon-close"></i></div>
    </div>
    <div class="greenWave">
      <div class="item">
        <div class="dir-text">{{$t('openatc.greenwaveoptimize.directionOptionup')}}</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.up.width}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.waveWidth')}}(s)</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.up.distance}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.distance')}}(m)</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.up.speed}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.speed1')}}(km/h)</div>
      </div>
      <div class="item-line"></div>
      <div class="item">
        <div class="dir-text">{{$t('openatc.greenwaveoptimize.directionOptiondown')}}</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.down.width}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.waveWidth')}}(s)</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.down.distance}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.distance')}}(m)</div>
      </div>
      <div class="item">
        <div class="num">{{greenWaveParam.realtimeGreenWave && greenWaveParam.realtimeGreenWave.down.speed}}</div>
        <div class="text">{{$t('openatc.greenwaveoptimize.speed1')}}(km/h)</div>
      </div>
    </div>
    <div class="line"></div>
    <div class="direction">
      <div class="planchart-name">{{$t('openatc.devicemanager.timeSpaceGraph')}}</div>
      <div class="direction-icon">
        <div class='item' @click="onLineUpClick">
          <div class="label">
            <div :class="isShowUp ? 'line-up' : 'line-up-selected'"></div>
          </div>
          <div class="value">{{$t('openatc.greenwaveoptimize.directionOptionup')}}</div>
        </div>
        <div class="item" @click="onLineDownClick">
          <div class="label">
            <div :class="isShowDown ? 'line-down' : 'line-down-selected'"></div>
          </div>
          <div class="value">{{$t('openatc.greenwaveoptimize.directionOptiondown')}}</div>
        </div>
      </div>
    </div>
    <div class="params" v-if="false">
      <div class="param">
        <div class="label">
          {{$t('openatc.greenwaveoptimize.patternName') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('openatc.greenwaveoptimize.coordinationstrategy') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('openatc.greenwaveoptimize.coordinationdirection') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('openatc.greenwaveoptimize.keyintersection') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('edge.date.month') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('edge.date.day') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('edge.date.date') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('openatc.greenwaveoptimize.period') + ':'}}
        </div>
        <div class="value">
          123
        </div>
      </div>
    </div>
    <div id="echarts" class="chart"></div>
</div>
</template>

<script>
import * as echarts from 'echarts'
import L from 'leaflet'
// @ts-ignore
import 'leaflet-polylinedecorator'
import CDTModel from '../../../compose/components/planChart/coordinationModel.js'
import { GetAllRoute, getAllPatternOfRoute, getAllFeatureOfRoute, getAllPhaseOfRoute, getBandwidth } from '../../../../api/route'
import { GetAllDevice, GetDeviceByIds } from '../../../../api/device'
import { getMessageByCode } from '../../../../utils/responseMessage'
export default {
  name: 'greenWaveCharts',
  components: {},
  props: {
    isShowPanel: {
      type: Boolean,
      default: true
    },
    params: {
      type: Object,
      default: () => {
        return {
          type: '1', // '1' intersection '2' route
          row: {}
        }
      }
    }
  },
  data () {
    return {
      greenWaveParam: {},
      isPanelShow: true,
      routeOptimizeMap: new Map(),
      allDevice: [],
      routeName: '--',
      routeLayer: '',
      deviceMarks: [],
      deviceGroupLayer: '',
      deviceFaultIcon: require('../../../../assets/gis/devicefault.png'),
      // deviceOnlineIcon: require('../../../../assets/gis/deviceonline.png'),
      // @ts-ignore
      deviceOnlineIcon: require('../../../../assets/gis/在线.svg'),
      // @ts-ignore
      deviceNotOnlineIcon: require('../../../../assets/gis/离线.svg'),
      direction: 'all',
      isShowUp: true,
      isShowDown: true,
      routerData: {},
      isShowUpCard: false,
      isShowDownCard: false,
      green: [],
      newRouteOptions: {
        color: '#5acd4c'
      },
      routeOptions: {
        color: '#909399'
      },
      chooseRouteId: 0,
      oldPolyline: '',
      containerWidth: 0,
      containerHeight: 0
    }
  },
  watch: {
    params: {
      // @ts-ignore
      handler: async function (val, oldVal) {
        console.log('received routeOptimize params:', val, oldVal)
        // check repeat
        if (val && oldVal && val.row && val.row.id === oldVal.row.id) {
          console.log('same route id')
          return false
        }
        this.clearLayer()
        if (val && val.row) {
          this.direction = 'all'
          this.isShowUp = true
          this.isShowDown = true
          this.chooseId = val.row.id
          // @ts-ignore
          this.isPanelShow = true
          // @ts-ignore
          this.routeData = val.row
          this.chooseRouteId = this.routeData.id
          this.allRoute = [val.row]
          await this.getAllDevice()
          // this.allFeature = await this.getAllFeatureOfRoute(this.chooseRouteId)
          this.allPatternList = await this.getAllPatternOfRoute(this.chooseRouteId)
          this.allPhaseList = await this.getAllPhaseOfRoute(this.chooseRouteId)
          // @ts-ignore
          this.map = window.map
          await this.onDeviceIdsChange()
          this.createRouteOptimize([val.row])
          this.showPlanchart(this.chooseRouteId)
        } else {
          // todo
        }
      },
      // 深度观察监听
      deep: true
    }
  },
  mounted () {
    const _this = this
    this.isPanelShow = this.isShowPanel
    var doms = document.getElementsByClassName('showLayout')
    if (doms && doms.length > 0) {
      let w = doms[0]
      this.containerWidth = w.style.width
      this.containerHeight = w.style.height
      w.style.width = '760px'
    }
    // w.style.height = '600px'
    var dom = document.getElementById('echarts')
    _this.myChart = echarts.init(dom)
    _this.CDTModel = new CDTModel()
    window.onresize = function () {
      _this.myChart.resize()
    }
  },
  created () {
  },
  methods: {
    onLineUpClick () {
      this.isShowUp = !this.isShowUp
      let direction = this.getDirection(this.isShowUp, this.isShowDown)
      this.direction = direction
      this.showPlanchart(this.chooseRouteId)
    },
    onLineDownClick () {
      this.isShowDown = !this.isShowDown
      let direction = this.getDirection(this.isShowUp, this.isShowDown)
      this.direction = direction
      this.showPlanchart(this.chooseRouteId)
    },
    getDirection (isShowUp, isShowDown) {
      let direction = 'all'
      if (isShowUp && isShowDown) {
        direction = 'all'
      } else if (!isShowUp && !isShowDown) {
        direction = ''
      } else if (isShowUp) {
        direction = 'up'
      } else if (isShowDown) {
        direction = 'down'
      }
      return direction
    },
    onCloseClick () {
      this.$emit('onCloseClick')
      this.isPanelShow = !this.isPanelShow
    },
    async init () {
      this.map = window.map
      await this.getAllDevice()
      this.getAllRouteOptimize()
    },
    getAllDevice () {
      return new Promise((resolve, reject) => {
        GetAllDevice().then((data) => {
          let res = data.data
          if (res.success) {
            this.allDevice = res.data
            resolve(res.data)
          } else {
            console.log(res.message)
            resolve([])
          }
        }, () => {
          console.log('GetAllDevice Error')
          reject(new Error('GetAllDevice Error'))
        })
      })
    },
    getAllRouteOptimize () {
      if (this.routeLayer !== '') {
        console.log('协调路线图层已存在！')
      }
      GetAllRoute().then((data) => {
        // 获取所有路线信息成功
        let res = data.data
        if (res.success) {
          this.allRoute = res.data
          // let list = this.allRoute.filter(item => item.id === this.chooseRouteId)
          // this.createRouteOptimize(list)
        } else {
          console.log(data.message)
        }
      }, () => {
        console.log('getAllRouteOptimize Error')
      })
    },
    createRouteOptimize (list) {
      if (!list) {
        return false
      }
      let dataList = JSON.parse(JSON.stringify(list))
      let _this = this
      let polylines = []
      this.deviceMarks = []
      let i = 0
      for (let data of dataList) {
        if (data.devs.length === 0) continue
        i++
        let geometry = _this.getGeometry(data)
        // let routeId = data.id
        let status = data.enable
        var polylineOptions = {}
        if (i === 1) {
          polylineOptions = {
          // color: status ? '#67c23a' : '#007dc5',
            color: this.newRouteOptions.color,
            weight: 12,
            routeId: data.id,
            status: status,
            name: data.name,
            keyintsid: data.keyintsid,
            geometry: geometry
          // opacity: 0.9
          }
          this.chooseRouteId = data.id
        } else {
          polylineOptions = {
          // color: status ? '#67c23a' : '#007dc5',
            color: '#909399',
            weight: 10,
            routeId: data.id,
            status: status,
            name: data.name,
            keyintsid: data.keyintsid,
            geometry: geometry
          // opacity: 0.9
          }
        }
        let polyline = L.polyline(geometry, polylineOptions).on('click', this.onPolylineClick)
        if (i === 1) {
          this.oldPolyline = polyline
          // this.showPlanchart(data.id)
          this.$emit('onRouteChange', geometry)
        }
        polylines.push(polyline)
        // _this.map.addLayer(polyline)
      }
      this.deviceGroupLayer = L.layerGroup(this.deviceMarks)
      _this.map.addLayer(this.deviceGroupLayer)
      _this.routeLayer = L.layerGroup(polylines)
      _this.map.addLayer(_this.routeLayer)
      // 轨迹方向箭头
      // @ts-ignore
      _this.decoratorLayer = L.polylineDecorator(polylines, {
        patterns: [{
          repeat: 50,
          // @ts-ignore
          symbol: L.Symbol.arrowHead({
            pixelSize: 5,
            headAngle: 75,
            polygon: false,
            pathOptions: {
              stroke: true,
              weight: 2,
              color: '#FFFFFF'
            }
          })
        }]
      }).addTo(_this.map)
      this.addRoutePopup()
      this.addMarkerPopup()
    },
    onPolylineClick (e) {
      let routeId = e.target.options.routeId
      if (this.chooseRouteId !== routeId) {
        e.target.setStyle(this.newRouteOptions)
        this.oldPolyline.setStyle(this.routeOptions)
        this.oldPolyline = e.target
        this.chooseRouteId = routeId
        let geometry = e.target.options.geometry
        this.$emit('onRouteChange', geometry)
      }
      // e.target.setStyle(this.newRouteOptions)
      this.showPlanchart(routeId)
    },
    addMarkerPopup () {
      let _this = this
      this.deviceGroupLayer.eachLayer(function (layer) {
        let options = layer.options.icon.options
        let devData = options.alt
        let content = _this.getMarkerPopupContent(devData)
        layer.bindPopup(content)
      })
    },
    getMarkerPopupContent (devData) {
      let agentid = devData.agentid
      let content =
      `
        <div> ${this.$t('openatc.gis.crossRoad')}${agentid}</div>
      `
      return content
    },
    addRoutePopup () {
      let _this = this
      _this.routeLayer.eachLayer(function (layer) {
        let content = _this.getPopupContent(layer.options)
        layer.bindPopup(content)
      })
    },
    getPopupContent (data) {
      let routeName = data.name
      // let status = data.status
      let keyintsid = data.keyintsid === undefined ? '--' : data.keyintsid
      let html = ''
      html = '<div><div style="font-size: 16px; font-weight: bold; font-stretch: normal; color: #303133;">' + routeName + '</div><div style="width: 150px; height: 1px; background-color: #004e61; border: solid 1px #e7e7e7; margin-top: 10px;"></div><div style="font-size: 14px; font-weight: normal; font-stretch: normal; color: #303133; margin-top: 10px;">' + this.$t('openatc.devicemanager.keyintersection') + keyintsid + '</div></div></div>'
      return html
    },
    getGeometry (data) {
      let devs = data.devs
      const avgIndex = Math.floor(devs.length / 2)
      devs.sort((a, b) => {
        return a.sortid > b.sortid
      })
      let coordinatesList = []
      for (let i = 0; i < devs.length; i++) {
        let dev = devs[i]
        let agentid = dev.agentid
        let deviceInfo = this.allDevice.filter((item) => {
          return item.agentid === agentid
        })
        if (deviceInfo.length === 0 || deviceInfo[0].geometry === undefined) continue
        let latlngs = [deviceInfo[0].geometry.coordinates[1], deviceInfo[0].geometry.coordinates[0]]
        coordinatesList.push(latlngs)
        let iconUrl = this.deviceFaultIcon
        if (deviceInfo[0].state === 'UP') {
          iconUrl = this.deviceOnlineIcon
        } else if (deviceInfo[0].state === 'DOWN') {
          iconUrl = this.deviceNotOnlineIcon
        }
        const circleClass = 'lmap-span ' + (this.params.type === '1' ? 'lmap-span-group' : 'lmap-span-optimize')
        const html = `<div class="lmap-container"><div class="${circleClass}">${i + 1}</div><img class="lmap-image" src="${iconUrl}"/></div>`
        let DefaultIcon2 = L.divIcon({
          title: dev.state,
          alt: dev,
          className: 'lmap-icon',
          html: html,
          iconSize: [42, 31], //  图标的大小
          iconAnchor: [12, 58], //  图标将对应标记点的位置
          popupAnchor: [1, -34] // 该点是相对于iconAnchor弹出信息的位置
        })
        let deviceMark = L.marker(latlngs, { icon: DefaultIcon2 }).addTo(this.map)
        this.deviceMarks.push(deviceMark)
        if (i === avgIndex) {
          // @ts-ignore
          this.map && this.map.flyTo(latlngs)
        }
      }
      return coordinatesList
    },
    getAllPatternOfRoute (id) {
      return new Promise((resolve, reject) => {
        getAllPatternOfRoute(id).then((data) => {
          let res = data.data
          if (res.success) {
            // this.allDevice = res.data
            resolve(res.data.devs)
          } else {
            let agentid = res.data.data.agentid
            let commomMsg = this.$t('openatc.greenwaveoptimize.device') + agentid
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
              // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
              }
            } else {
              this.$message.error(parrenterror + ',' + commomMsg)
            }
            resolve([])
          }
        }, () => {
          console.log('GetAllDevice Error')
          reject(new Error('GetAllDevice Error'))
        })
      })
    },
    getAllPhaseOfRoute (id) {
      return new Promise((resolve, reject) => {
        getAllPhaseOfRoute(id).then((data) => {
          let res = data.data
          if (res.success) {
            // this.allDevice = res.data
            resolve(res.data.devs)
          } else {
            let agentid = res.data.data.agentid
            let commomMsg = this.$t('openatc.greenwaveoptimize.device') + agentid
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
              // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
              }
            } else {
              this.$message.error(parrenterror + ',' + commomMsg)
            }
            resolve([])
          }
        }, () => {
          console.log('GetAllDevice Error')
          reject(new Error('GetAllDevice Error'))
        })
      })
    },
    getAllFeatureOfRoute (id) {
      return new Promise((resolve, reject) => {
        getAllFeatureOfRoute(id).then((data) => {
          let res = data.data
          if (res.success) {
            // this.allDevice = res.data
            resolve(res.data.devs)
          } else {
            let agentid = res.data.data.agentid
            let commomMsg = this.$t('openatc.greenwaveoptimize.device') + agentid
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
              // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
              }
            } else {
              this.$message.error(parrenterror + ',' + commomMsg)
            }
            resolve([])
          }
        }, () => {
          console.log('GetAllDevice Error')
          reject(new Error('GetAllDevice Error'))
        })
      })
    },
    async showPlanchart (routeId) {
      this.clearMyChart()
      let greenwave = []
      let routeData = this.allRoute.filter((item) => {
        return item.id === routeId
      })[0]
      this.routeName = routeData.name
      // let patternList = await this.getAllPatternOfRoute(routeId)
      let patternList = this.allPatternList
      if (greenwave.length === 0) {
        this.isShowUpCard = false
        this.isShowDownCard = false
      } else {
        this.green = greenwave
        if (this.direction === 'up') {
          this.isShowUpCard = true
        } else if (this.direction === 'down') {
          this.isShowDownCard = true
        } else if (this.direction === 'all') {
          this.isShowUpCard = true
          this.isShowDownCard = true
        }
        this.CDTModel.greenwave = greenwave
      }
      if (patternList.length === 0) {
        // this.$message.error('方案为空！')
        return
      }
      let devs = routeData.devs
      for (let inter of devs) {
        inter.patternList = []
        let id = inter.agentid
        let patternId = this.getActurlPatternid(inter.agentid)
        let pattern = patternList.filter(pat => pat.agentid === id)[0]
        if (pattern.feature !== undefined && pattern.feature.patternList.length !== 0) {
          let allPatternList = pattern.feature.patternList
          if (Array.isArray(allPatternList)) {
            let currPatternList = allPatternList.filter(apl => apl.id === patternId)
            inter.patternList = currPatternList
          } else {
            let tempList = []
            tempList.push(allPatternList)
            inter.patternList = tempList
          }
          inter.feature = {
            patternList: inter.patternList
          }
          // check controlPattern
          const pattern0 = allPatternList[0]
          if (pattern0.contrloType === 'stage' || !pattern0.rings || pattern0.rings.length === 0) {
            console.log('路口： ' + id + ' 阶段模式控制中', pattern)
            // return false
          }
        }
      }

      // set dir all
      routeData.direction = this.direction
      this.realtimeRouteData.direction = this.direction
      // this.CDTModel.rourte = routeData
      this.CDTModel.rourte = this.realtimeRouteData
      this.realtimeRouteData.devs.map(dev => {
        let id = dev.patternid
        const pattern = dev.patternList.find(p => p.id === id)
        if (pattern) {
          let targetPattern = {...dev.patternList[0], ...pattern}
          if (targetPattern.rings.length === 0 || targetPattern.contrloType === 'stage') {
            // reset route phaseid
            this.resetRoutePhaseId(dev, targetPattern)
          }
          if (targetPattern.rings.length === 0 || targetPattern.contrloType === 'stage') {
            let stagesList = targetPattern.stagesList
            if (stagesList && stagesList.length > 0) {
              let tempRings = stagesList.map((item, index) => {
                let ringItem = {
                  id: index + 1,
                  value: item.stageSplit
                }
                return ringItem
              })
              targetPattern.rings = [tempRings]
            }
          }
          dev.patternList[0] = targetPattern
        }
      })
      this.routerData = routeData
      this.clearMyChart()
      this.myChart.setOption(this.CDTModel.RenderOption())
    },
    resetRoutePhaseId (routeData, targetPattern) {
      let forwardphaseid = routeData.forwardphaseid
      let backphaseid = routeData.backphaseid
      let targetForwardphaseid = -1
      let targetBackphaseid = -1
      let stagesList = targetPattern.stagesList
      for (let i = 0; i < stagesList.length; i++) {
        let stageItem = stagesList[i]
        if (targetForwardphaseid < 0 && stageItem.phases.includes(forwardphaseid)) {
          targetForwardphaseid = i + 1
        }
        if (targetBackphaseid < 0 && stageItem.phases.includes(backphaseid)) {
          targetBackphaseid = i + 1
        }
        if (targetForwardphaseid > 0 && targetBackphaseid > 0) {
          break
        }
      }
      routeData.forwardphaseid = targetForwardphaseid
      routeData.backphaseid = targetBackphaseid
    },
    clearMyChart () {
      if (this.myChart.getOption() !== undefined) {
        this.myChart.clear()
      }
    },
    clearLayer () {
      this.clearMyChart()
      let _this = this
      if (_this.routeLayer !== '') {
        _this.map.removeLayer(_this.routeLayer)
        _this.routeLayer = ''
      }
      if (_this.deviceGroupLayer !== '') {
        _this.map.removeLayer(_this.deviceGroupLayer)
        // _this.deviceGroupLayer.clearLayers()
        _this.deviceGroupLayer = ''
      }
      if (_this.decoratorLayer) {
        _this.map.removeLayer(_this.decoratorLayer)
        // _this.deviceGroupLayer.clearLayers()
        _this.decoratorLayer = ''
      }
      if (_this.chooseRouteId !== 0) {
        _this.chooseRouteId = 0
      }
      if (_this.oldPolyline !== '') {
        _this.oldPolyline = ''
      }
    },
    async onDeviceIdsChange () {
      if (this.chooseRouteId) {
        let currentDeviceIds = []
        let currentRoute = this.allRoute.filter(item => item.id === this.chooseRouteId)[0]
        let devs = currentRoute.devs
        for (let dev of devs) {
          currentDeviceIds.push(dev.agentid)
        }
        this.$emit('onDeviceIdsChange', currentDeviceIds)
        await this.getDeviceByIds(this.routeData)
      }
    // eslint-disable-next-line comma-dangle
    },
    async getDeviceByIds (routeData) {
      // 获取设备表格信息
      let realtimeRouteData = JSON.parse(JSON.stringify(routeData))
      this.deviceIds = realtimeRouteData.devs.map(ele => ele.agentid)
      await GetDeviceByIds(this.deviceIds).then(async res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devicesData = res.data.data
        // 取路口对应的实际方案id
        let devs = realtimeRouteData.devs
        for (let inter of devs) {
          inter.patternid = this.getActurlPatternid(inter.agentid)
          let devFeature = this.allPatternList.find(item => item.agentid === inter.agentid)
          inter.patternList = devFeature.feature.patternList
          let devPhaseFeature = this.allPhaseList.find(item => item.agentid === inter.agentid)
          inter.phaseList = devPhaseFeature.feature.phaseList
        }
        let realtimeGreenWave = await this.getBandwidth(realtimeRouteData)
        const greenWaveParam = this.getGreenWaveParam([], realtimeGreenWave)
        console.log('greenWaveParam', greenWaveParam)
        this.greenWaveParam = greenWaveParam
        this.realtimeRouteData = realtimeRouteData
      })
    },
    getGenerateParam (routeData, bizType = 0) { // bizType： 1 generate专用
      let route = JSON.parse(JSON.stringify(routeData))
      let param = {
        'id': route.id,
        'name': route.name,
        'keyintsid': route.keyintsid,
        'direction': route.direction,
        'optstrategy': route.optstrategy,
        'upspeed': route.upspeed,
        'downspeed': route.downspeed,
        'type': route.type ? route.type : 0,
        'devs': route.devs
      }
      let devs = route.devs
      for (let inter of devs) {
        let patternList = inter.patternList.map(item => {
          let pattern = {
            'id': item.id,
            'desc': item.desc,
            'offset': item.offset,
            'cycle': item.cycle,
            'rings': item.rings
          }
          // add some feature
          let addPropertity = this.getAddFeatute(inter.agentid, item.id)
          pattern = {...pattern, ...addPropertity}
          return pattern
        })
        let phaseList = inter.phaseList.map(item => {
          // let pattern = {
          //   'id': item.id,
          //   'concurrent': item.concurrent
          // }
          let pattern = {...item}
          return pattern
        })
        let feature = {
          patternList: patternList,
          phaseList: phaseList
        }
        inter.routeid = param.id
        inter.feature = feature
        delete inter.id
        delete inter.name
      }
      // param = route
      param.devs = param.devs.map((item, index) => {
        let dev = {
          'agentid': item.agentid,
          'routeid': item.routeid,
          'forwardphaseid': item.forwardphaseid,
          'backphaseid': item.backphaseid,
          'distance': item.distance,
          'width': item.width,
          'sortid': item.sortid ? item.sortid : index + 1,
          'patternid': item.patternid,
          'feature': item.feature,
          'fixedtimeplantype': item.fixedtimeplantype,
          'phases': item.phases
        }
        if (bizType === 1) {
          dev.feature.patternList = dev.feature.patternList.filter(pattern => pattern.id === dev.patternid)
        }
        return dev
      })
      return param
    },
    getAddFeatute (agentid, patternId) {
      let addPropertity = {
        barriers: [],
        stages: [],
        stagesList: []
      }
      for (let pdev of this.allPatternList) {
        if (pdev.agentid === agentid) {
          let pPatternList = pdev.feature.patternList
          let pPattern = pPatternList.find(pItem => pItem.id === patternId)
          if (pPattern) {
            addPropertity = {
              barriers: pPattern.barriers,
              stages: pPattern.stages,
              stagesList: pPattern.stagesList
            }
          }
          break
        }
      }
      return addPropertity
    },
    async getBandwidth (routeData) {
      let param = this.getGenerateParam(routeData, 1)
      let greenwave = []
      await getBandwidth(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        greenwave = res.data.data.greenwave
      })
      return greenwave
    },
    getGreenWaveParam (greenWave, realtimeGreenWave) {
      let res = {}
      if (greenWave && realtimeGreenWave) {
        let up = greenWave.find(item => item.type === 'up')
        let down = greenWave.find(item => item.type === 'down')
        let realtimeUp = realtimeGreenWave.find(item => item.type === 'up')
        let realtimeDown = realtimeGreenWave.find(item => item.type === 'down')
        res = {
          greenWave: {
            up: up,
            down: down
          },
          realtimeGreenWave: {
            up: realtimeUp,
            down: realtimeDown
          }
        }
      }
      return res
    },
    getActurlPatternid (agentid) {
      let devinfo = this.devicesData.filter(dev => dev.agentid === agentid)[0]
      if (devinfo && devinfo.patternid !== undefined) {
        return devinfo.patternid
      } else {
        return 1
      }
    }
  },
  destroyed () {
    this.clearLayer()
    // var w = document.getElementsByClassName('showLayout')[0]
    // w.style.width = this.containerWidth
    // w.style.height = this.containerHeight
  }
}
</script>

<style lang="scss">
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 5px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
 .lmap-image {
    width: 32PX;
    height: 31PX;
    margin-top: -3PX;
  }

  .lmap-span {
    width: 30PX;
    height: 30PX;
    margin-left: -4PX;
    border-radius: 50%;
    background-color: red;
    font-family: SourceHanSansCN-Bold;
    font-size: 16PX;
    font-weight: bold;
    font-stretch: normal;
    line-height: 14PX;
    letter-spacing: 0PX;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #ffffff;
    position: relative;
    z-index: 9999;
  }
  .lmap-span-optimize {
    background-color: #5acd4c;
  }
  .lmap-span-group {
    background-color: #e0ac24;
  }
  .lmap-span-route {
    background-color: #37ccaa;
  }
</style>
